<?php
include('ZReader.php');
include('ZLeadItem.php');

class ZLeadReader extends ZReader
{
    /**
     * Generate command string
     * @return string
     */
    public function command() {
        return sprintf('leads %s %d %d %s %s %d %s %s %s %s %s'."\r\n",
            $this->session,
            $this->offset,
            $this->limit,
            $this->begin,
            $this->end,
            $this->timeZone,
            $this->languages,
            $this->types,
            $this->excludedIds,
            $this->excludedThreadIds,
            $this->query
        );
    }
    /**
     * Parse data that receive from server to object
     * @param $callback
     * @param $state
     * @return int
     */
    public function parse($callback, &$state) {
        $i          = 0;
        $arr        = array();
        $succeed    = false;
        $total      = $this->readNum();
        $count      = 0;

        //Read data while not end of file
        while (!$this->eof()) {
            //Read the first block is the length of the data
            $numBytes = $this->readNum();

            if ($numBytes >= 0 && $numBytes < 0xffffffff) {
                if ($i  < 8) {
                    $arr[] = $this->readStr($numBytes);
                } else {
                    $arr[] = $this->readNum($numBytes);
                }
                $i++;
                //Enough a item
                if ($i == 11) {
                    $item = new ZLeadItem($arr[0], $arr[1], $arr[2], $arr[3], $arr[4], $arr[5], $arr[6], $arr[7], $arr[8], $arr[9], $arr[10]);

                    $arr = array();
                    $i = 0;
                    if (is_callable($callback)) {
                        $callback($item, $total);
                    }

                    $count++;
                }
                //Not succeeded
                $succeed = false;
            }
            else if ($numBytes == 0xffffffff) {
                $succeed = true;
            }
        }

        $state = $succeed ? ($count > 0 ? 1 : 0) : -1;
        return $count;
    }

    /**
     * @param null  $callback   callback function when receive data
     * @param int   $offset     started getting offset
     * @param int   $limit      item getting limitation
     * @return int Number of item received
     * @throws Exception
     */
    public function read($callback = null, $offset = 0, $limit = 100) {
        return parent::readData($callback, $offset, $limit);
    }
}

?>